package com.kongchengji.spider.picServer;


import com.alibaba.fastjson.JSONObject;
import com.kongchengji.spider.station.dao.OnlyPicIdentifyingDao;
import com.kongchengji.spider.station.domain.PictureModelDO;
import com.kongchengji.spider.util.HttpClientPool;
import com.kongchengji.spider.util.R;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Component
public class UpdatePicServer {
    @Value("${picServer.updatePicUrl}")
     private String updatePicUrl;
    @Autowired
    OnlyPicIdentifyingDao onlyPicIdentifyingDao;
    @Transactional(rollbackFor=Exception.class)
    public void updatePic(PictureModelDO pictureModelDO) throws IOException {
        Logger logger = LoggerFactory.getLogger(UpdatePicServer.class);
        HttpPost httpPost = new HttpPost(updatePicUrl);
        HttpClient httpClient = HttpClientPool.getHttpClient();
        List<NameValuePair> pairs = new ArrayList<>();
        CloseableHttpResponse response = null;
        pairs.add(new BasicNameValuePair("pictureModelDOJson",pictureModelDO.toString()));
        try {
//            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(pairs);
            HttpEntity reqEntity = EntityBuilder
                    .create()
                    .setContentType(
                            ContentType.create(
                                    "application/x-www-form-urlencoded",
                                    Consts.UTF_8)).setParameters(pairs).build();
            httpPost.setEntity(reqEntity);
            response = (CloseableHttpResponse) httpClient.execute(httpPost);
            //可以转成R对象则说明请求成功返回
            R r = JSONObject.parseObject( EntityUtils.toString(response.getEntity()),R.class);
            logger.info(r.toString());
            //将图集的唯一标识存入本地数据库,用于判断该图集是否已经爬取过
            onlyPicIdentifyingDao.add(pictureModelDO.getThumbnailUrl(),pictureModelDO.getStationId());
        } finally {
            if(response != null){
               response.close();
            }
            if(httpPost != null){
                httpPost.releaseConnection();
            }
        }
    }

}
